/*
 * @Author: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @Date: 2022-10-10 16:25:31
 * @LastEditors: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @LastEditTime: 2022-10-26 16:59:01
 * @FilePath: \实训二——宏业找房\egg\app\controller\home.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
'use strict';

const { Controller } = require('egg');
const jwt = require('jsonwebtoken');
class LoginController extends Controller {
    // 登录
    async login() {
        const { ctx } = this;
        const { username, password } = ctx.request.body;
        const post = await this.app.mysql.get('login', { username, password });
        if (post) {
            const token = jwt.sign({ username, password }, 'gzd', {
                expiresIn: '800000'
            });
            ctx.body = {
                code: 200,
                user:post,
                msg: '登录成功',
                token,

            }
        } else {
            ctx.body = {
                code: 500,
                msg: '登录失败'
            }
        }
    }

    // 注册
    async sign() {
        const { ctx } = this;
        const { username, password } = ctx.request.body;
        const post = await this.app.mysql.get('login', { username,password});
        
        if (post) {
            // 账号已存在
            ctx.body = {
                code: 404,
                msg: '账号已存在'
            }
        } else {
            // 账号不存在
            const result = await this.app.mysql.insert('login', { username,password });
            if (result) {
                const post = await this.app.mysql.get('login', { username, password });
                ctx.body = {
                    code: 200,
                    msg: '账号注册成功',
                    list: post
                }
            } else {
                ctx.body = {
                    code: 500,
                    msg: '账号注册失败',
                }
            }
        }
    }

}

module.exports = LoginController;
